<template>
  <div class="unsafe-driving-alarm bg-background text-foreground p-6">
    <h2 class="mb-6 text-2xl font-bold">不安全驾驶行为报警</h2>

    <div class="bg-card text-card-foreground mb-4 rounded p-4 shadow">
      <!-- Search Form -->
      <QueryForm :model="filters" :formItems="formItems" @search="loadData" @reset="resetFilters" />
    </div>


    <!-- Action Buttons -->
    <div class="mb-4 space-x-2">
      <!-- <button @click="addNew" class="btn btn-primary">
          新增
        </button>
        <button @click="deleteSelected" class="btn btn-destructive">
          删除
        </button>
        <label for="importFile" class="btn btn-secondary">
          导入
        </label>
        <input
          id="importFile"
          type="file"
          @change="importData"
          accept=".xlsx, .xls"
          class="hidden"
        /> -->
      <!-- <button @click="exportData" class="btn btn-secondary">导出</button> -->
      <el-button @click="exportData" style="width: 75px; height: 30px;">导出</el-button>
      <!-- <button @click="openSettings" class="btn btn-secondary ml-auto">
          设置
        </button> -->
      <el-button type="primary" @click="openSettings"
        style="width: 75px; height: 30px; float: right;margin-right: 48px;">设置</el-button>
    </div>
    <!-- Data Table -->
    <div class="bg-card text-card-foreground my-6 rounded shadow-md">
      <!-- <div class="overflow-x-auto">
        <table class="divide-border min-w-full divide-y">
          <thead class="bg-muted">
            <tr>
              <th class="checkbox-cell">
                <input type="checkbox" :checked="selectAll" @change="toggleSelectAll" class="checkbox" />
              </th>
              <th v-for="header in tableHeaders" :key="header" class="table-header">
                {{ header }}
              </th>
            </tr>
          </thead>
          <tbody class="bg-card text-card-foreground divide-border divide-y">
            <tr v-for="(item, index) in paginatedData" :key="item.id" class="hover:bg-muted/50">
              <td class="table-cell w-[60px]">
                <input type="checkbox" v-model="item.selected" class="checkbox" />
              </td>
              <td class="table-cell">{{ startIndex + index + 1 }}</td>
              <td class="table-cell">{{ item.alarm_code }}</td>
              <td class="table-cell">{{ item.alarm_type }}</td>
              <td class="table-cell">{{ item.description }}</td>
              <td class="table-cell">{{ item.location }}</td>
              <td class="table-cell">{{ formatDateTime(item.alarm_time) }}</td>
              <td class="table-cell">{{ item.status }}</td>
              <td class="table-cell">{{ item.handling_person || '-' }}</td>
              <td class="table-cell">
                {{ formatDateTime(item.handling_time) || '-' }}
              </td>
              <td class="table-cell">{{ item.handling_result || '-' }}</td>
              <td class="table-cell">
                <button @click="editItem(item)" class="btn btn-sm btn-secondary mr-2">编辑</button>
                <button @click="viewDetails(item)" class="btn btn-sm btn-secondary">查看</button>
              </td>
            </tr>
          </tbody>
        </table>
      </div> -->
      <el-table v-loading="loading" :data="paginatedData" style="width: 100%" ref="table" align="center"
        class="data-table" :header-cell-style="headerCellStyle">
        <!-- <el-table-column type="selection" width="55"></el-table-column> -->
        <el-table-column label="序号" width="55" header-align="center" align="center">
          <template #default="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column prop="EVENT_CODE" label="事件编码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="EVENT_TYPE" label="事件类型" header-align="center" align="center">

        </el-table-column>
        <el-table-column prop="EVENT_DESCRIPTION" label="事件描述" header-align="center" align="center"></el-table-column>
        <el-table-column prop="PLACE_OCCURRENCE" label="发生地点" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="DATE_OCCURRENCE" label="发生日期" header-align="center" align="center">
          <template #default="scope">
            {{ formatDateTime(scope.row.DATE_OCCURRENCE) }}
          </template>
        </el-table-column>
        <el-table-column prop="MONITORING_EQUIPMENT" label="监测设备" header-align="center" align="center">
        </el-table-column>
        <el-table-column prop="LICENSE_NUMBER" label="车牌号码" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NAME" label="驾驶员姓名" header-align="center" align="center"></el-table-column>
        <el-table-column prop="DRIVER_NUMBER" label="联系方式" header-align="center" align="center"></el-table-column>
        <el-table-column prop="REMARK" label="备注" header-align="center" align="center"></el-table-column>
      </el-table>
    </div>
    <!-- Pagination -->
    <div class="border-border flex items-center justify-between border-t px-4 py-3 sm:px-6">
      <div>
        <p class="text-sm text-muted-foreground">
          一共检索到 <span class="font-medium total-num">{{ totalItems }}</span> 条信息
        </p>
      </div>
      <div class="flex items-center space-x-2">
        <button @click="prevPage" :disabled="currentPage === 1" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === 1 }">
          上一页
        </button>
        <span class="text-sm text-muted-foreground">
          {{ currentPage }} / {{ totalPages }}
        </span>
        <button @click="nextPage" :disabled="currentPage === totalPages" class="btn btn-secondary btn-sm"
          :class="{ 'opacity-50 cursor-not-allowed': currentPage === totalPages }">
          下一页
        </button>
      </div>
    </div>


    <!-- 替换 el-dialog 为原生对话框 -->
    <Teleport to="body">
      <div v-if="dialogVisible"
        class="bg-background/80 fixed inset-0 flex items-center justify-center backdrop-blur-sm">
        <div class="bg-card text-card-foreground w-[800px] rounded-lg p-5 shadow-xl">
          <div class="mb-4 flex items-center justify-between">
            <h3 class="text-lg font-bold">
              {{ isEditing ? '编辑事件' : '新增事件' }}
            </h3>
            <button @click="closeDialog" class="text-muted-foreground hover:text-foreground">
              <svg class="h-6 w-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"></path>
              </svg>
            </button>
          </div>

          <form @submit.prevent="saveIncident" class="space-y-4">
            <div>
              <label class="block text-sm font-medium">事件编码</label>
              <input v-model="formData.incidentCode" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">事件类型</label>
              <select v-model="formData.incidentType" class="input" required>
                <option value="一般事件">一般事件</option>
                <option value="紧急事件">紧急事件</option>
                <option value="重大事件">重大事件</option>
              </select>
            </div>
            <div>
              <label class="block text-sm font-medium">事件描</label>
              <input v-model="formData.description" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">发生地点</label>
              <input v-model="formData.location" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">发生日期</label>
              <input v-model="formData.date" type="datetime-local" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">监测设备</label>
              <input v-model="formData.monitoringDevice" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">车牌号</label>
              <input v-model="formData.licensePlate" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">驾驶员</label>
              <input v-model="formData.driver" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">联系方式</label>
              <input v-model="formData.contactNumber" class="input" required />
            </div>
            <div>
              <label class="block text-sm font-medium">备注</label>
              <textarea v-model="formData.notes" class="input" rows="3"></textarea>
            </div>

            <div class="flex justify-end space-x-2">
              <button type="button" @click="closeDialog" class="btn btn-secondary">
                取消
              </button>
              <button type="submit" class="btn btn-primary">确定</button>
            </div>
          </form>
        </div>
      </div>
    </Teleport>
    <el-dialog class="dialog-from dialog-set" v-model="showSettings" title="不安全驾驶行为规则设置" width="550" destroy-on-close
      align-center>
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>车辆超速行驶报警</strong>
        </div>
        <div class="box-content-item">
          <span>车辆速度限制：</span> <el-input class="set-input" type="number" v-model="setFrom.SPEEDING"
            style="width: 30px; height: 30px;font-size: 12px;" :disabled="radio1 == '关闭'" /> <span>km/h</span>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio1">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="set-der" />
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>车辆违停报警</strong>
        </div>
        <div class="box-content-item">
          <span>指定区域：</span><el-select class="set-select" v-model="setFrom.PARKING" placeholder="请选择"
            :disabled="radio2 == '关闭'">
            <el-option label="科技东路" value="科技东路" />
          </el-select>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio2">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="set-der" />
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>车辆不按车道通行报警</strong>
        </div>
        <div class="box-content-item">
          <span>起点：</span><el-select class="set-select" v-model="setFrom.FOLLOW_BEGIN" placeholder="请选择"
            :disabled="radio3 == '关闭'">
            <el-option label="科技东路" value="科技东路" />
          </el-select>
        </div>
        <div class="box-content-item" style="margin-top: 5px;">
          <span>终点：</span><el-select class="set-select" v-model="setFrom.FOLLOW_END" placeholder="请选择"
            :disabled="radio3 == '关闭'">
            <el-option label="科技东路" value="科技东路" />
          </el-select>
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio3">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <el-divider class="set-der" />
      <div class="body-set-item">
        <div class="box-title">
          <div class="box-set-color"></div><strong>车辆不按时段通行报警</strong>
        </div>
        <div class="box-content-item">
          <span>开始时间：</span> <input type="datetime-local" v-model="setFrom.TIME_BEGIN"
            class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
            :disabled="radio4 == '关闭'" />
        </div>
        <div class="box-content-item" style="margin-top: 5px;">
          <span>结束时间：</span> <input type="datetime-local" v-model="setFrom.TIME_END"
            class="input-time mt-1 block w-full rounded-md border-gray-300 focus:border-indigo-300 focus:ring focus:ring-indigo-200 focus:ring-opacity-50"
            :disabled="radio4 == '关闭'" />
        </div>
        <div class="box-content-item">
          <el-radio-group v-model="radio4">
            <el-radio value="启用" size="small">启用</el-radio>
            <el-radio value="关闭" size="small">关闭</el-radio>
          </el-radio-group>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="setSubmit">确认</el-button>
          <el-button @click="showSettings = false">
            取消
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import axios from 'axios'
import { getCurrentInstance } from 'vue'
const { proxy } = getCurrentInstance()
import * as XLSX from 'xlsx'
// import {
//   PlusIcon,
//   TrashIcon,
//   UploadIcon,
//   DownloadIcon,
//   SettingsIcon,
//   ChevronLeftIcon,
//   ChevronRightIcon,
// } from 'lucide-vue-next'

// 1. 声明所有响应式变量
const filters = ref({
  EVENT_CODE: '',
  EVENT_TYPE: '',
})
const apiBaseUrl = ref(proxy.$currentUrl + '/api/unsafe_driving_alarm')
const tableHeaders = [
  '序号',
  '事件编码',
  '事件类型',
  '事件描述',
  '发生地点',
  '发生时间',
  '处理状态',
  '处理人',
  '处理时间',
  '处理结果',
]

const incidentData = ref([])
const currentPage = ref(1)
const itemsPerPage = 10
const selectAll = ref(false)
const dialogVisible = ref(false)
const isEditing = ref(false)
const formData = ref({
  incidentCode: '',
  incidentType: '',
  description: '',
  location: '',
  date: '',
  monitoringDevice: '',
  licensePlate: '',
  driver: '',
  contactNumber: '',
  notes: '',
})
const pageSize = ref(10)
// 2. 添加计算属性
const totalItems = computed(() => incidentData.value.length)
const totalPages = computed(() => Math.ceil(totalItems.value / pageSize.value))

const paginatedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return incidentData.value.slice(start, end)
})

const displayedPages = computed(() => {
  const range = 2
  const pages = []
  for (
    let i = Math.max(1, currentPage.value - range);
    i <= Math.min(totalPages.value, currentPage.value + range);
    i++
  ) {
    pages.push(i)
  }
  return pages
})

// 3. 添加方法
const loadData = async () => {
  // 模拟API调用加载数据


  try {
    loading.value = true
    const response = await axios.get(`${apiBaseUrl.value}/search`, {
      params: filters.value,
    })
    // console.log('Received vehicle data:', response.data)
    incidentData.value = response.data
    loading.value = false
  } catch (error) {
    console.error('搜索不安全驾驶行为失败:', error)
    alert(
      '搜索不安全驾驶行为失败: ' + (error.response?.data?.message || error.message),
    )
  }
}

const resetFilters = () => {
  filters.value = {
    EVENT_CODE: '',
    EVENT_TYPE: '',
  }
  loadData()
  currentPage.value = 1
}

const addNew = () => {
  formData.value = {
    incidentCode: `SJ${String(incidentData.value.length + 1).padStart(4, '0')}`,
    incidentType: '',
    description: '',
    location: '',
    date: new Date().toISOString().slice(0, 16),
    monitoringDevice: '',
    licensePlate: '',
    driver: '',
    contactNumber: '',
    notes: '',
  }
  isEditing.value = false
  dialogVisible.value = true
}

const deleteSelected = () => {
  const selectedItems = incidentData.value.filter((item) => item.selected)
  if (selectedItems.length === 0) {
    alert('请选择要删除的记录')
    return
  }
  if (confirm(`确定要删除选中的 ${selectedItems.length} 条记录吗？`)) {
    incidentData.value = incidentData.value.filter((item) => !item.selected)
    selectAll.value = false
  }
}

const toggleSelectAll = () => {
  selectAll.value = !selectAll.value
  incidentData.value.forEach((item) => (item.selected = selectAll.value))
}
// 辅助函数
const getVehicleTypeText = (type) => {
  const types = {
    1: '一般事件',
    2: '紧急事件',
    3: '重大事件',
  }
  return types[type] || ''
}
// 添加格式化日期时间的辅助函数
const formatDateTimeForInput = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toISOString().slice(0, 16) // 格式为 "YYYY-MM-DDTHH:mm"
}

const formItems = ref([
  {
    label: '事件编码：',
    model: 'EVENT_CODE',
    type: 'input',
    placeholder: '请输入',
  },
  {
    label: '事件类型：',
    model: 'EVENT_TYPE',
    type: 'select',
    placeholder: '请选择',
    options: [
      { label: '请选择', value: '' },
      { label: '一般事件', value: '一般事件' },
      { label: '紧急事件', value: '紧急事件' },
      { label: '重大事件', value: '重大事件' },
    ],
  },
]);
// 修改 exportData 函数
const exportData = () => {
  const dataToExport = incidentData.value.map((item) => ({
    事件编码: item.EVENT_CODE,
    事件类型: item.EVENT_TYPE,
    事件描述: item.EVENT_DESCRIPTION,
    发生地点: item.PLACE_OCCURRENCE,
    发生日期: formatDateTime(item.DATE_OCCURRENCE),
    监测设备: item.MONITORING_EQUIPMENT,
    车牌号码: item.LICENSE_NUMBER,
    驾驶员姓名: item.DRIVER_NAME,
    联系方式: item.DRIVER_NUMBER,
    备注: item.REMARK,
  }))

  const worksheet = XLSX.utils.json_to_sheet(dataToExport)
  const workbook = XLSX.utils.book_new()
  XLSX.utils.book_append_sheet(workbook, worksheet, '不安全驾驶行为报警')

  // 生成二进制字符串作为文件内容
  const wbout = XLSX.write(workbook, { bookType: 'xlsx', type: 'binary' })

  // 将二进制字符串转换为Blob对象
  const blob = new Blob([s2ab(wbout)], { type: 'application/octet-stream' })

  // 创建下载链接并触发下载
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = '不安全驾驶行为报警.xlsx'
  link.click()
}

// 辅助函数：将字符串转换为ArrayBuffer
function s2ab(s) {
  const buf = new ArrayBuffer(s.length)
  const view = new Uint8Array(buf)
  for (let i = 0; i < s.length; i++) view[i] = s.charCodeAt(i) & 0xff
  return buf
}
// 表头样式
const headerCellStyle = {
  height: '30px', // 设置表头高度
  lineHeight: '30px', // 设置行高以垂直居中
  backgroundColor: '#f2f2f2', // 可选：设置背景颜色
  // fontSize: '16px', // 可选：设置字体大小
};
const rules = {
  EQUIPMENT_CODE: [
    { required: true, message: '请输入设备编码', trigger: 'blur' },
  ],
  STAFF_CODE: [
    { required: true, message: '请输入人员编码', trigger: 'blur' },
  ],
  STAFF_NAME: [
    { required: true, message: '请输入人员姓名', trigger: 'blur' },
  ],
  STAFF_TYPE: [
    { required: true, message: '请输入人员类型', trigger: 'change' },
  ],
  PASS_TIME: [
    { required: true, message: '请输入通行时间', trigger: 'change' },
  ],
  PASS_TYPE: [
    { required: true, message: '请输入通行类型', trigger: 'change' },
  ],
};
const formRef = ref(null)
const isDialogType = ref('')
const loading = ref(false)
// 添加格式化日期时间的函数
const formatDateTime = (dateTimeString) => {
  if (!dateTimeString) return ''
  const date = new Date(dateTimeString)
  return date.toLocaleString()
}
const prevPage = () => {
  if (currentPage.value > 1) {
    currentPage.value--
    loadData()
  }
}

const nextPage = () => {
  if (currentPage.value < totalPages.value) {
    currentPage.value++
    loadData()
  }
}
const showSettings = ref(false);
const openSettings = () => {
  showSettings.value = true
}
// 4. 初始化数据
onMounted(() => {
  loadData()
})

// 3. 修改对话框关闭函数
const closeDialog = () => {
  dialogVisible.value = false
  formData.value = {
    incidentCode: '',
    incidentType: '',
    description: '',
    location: '',
    date: '',
    monitoringDevice: '',
    licensePlate: '',
    driver: '',
    contactNumber: '',
    notes: '',
  }
}
const radio1 = ref('启用')
const radio2 = ref('启用')
const radio3 = ref('启用')
const radio4 = ref('启用')
const setFrom = ref({
  SPEEDING: 0,
  PARKING: '科技东路',
  FOLLOW_BEGIN: '科技东路',
  FOLLOW_END: '科技东路',
  TIME_BEGIN: '',
  TIME_END: '',
})
const setSubmit = () => {
  alert('设置成功');
  showSettings.value = false;
}
</script>

<style scoped>
.btn {
  @apply rounded-md px-4 py-2 font-medium transition duration-150 ease-in-out focus:outline-none focus:ring-2 focus:ring-offset-2;
}

.btn-primary {
  @apply bg-primary text-primary-foreground hover:bg-primary/90;
}

.btn-secondary {
  @apply bg-secondary text-secondary-foreground hover:bg-secondary/80;
}

.btn-destructive {
  @apply bg-destructive text-destructive-foreground hover:bg-destructive/90;
}
</style>
<style lass="scss" scoped>
.dialog-footer {
  display: flex;
  justify-content: center;
  /* 按钮居中对齐 */
}

.total-num {
  color: #02a7f0;
  font-size: 28px;
}

:deep(.dialog-from.el-dialog) {
  padding-top: 0;
  padding-left: 0;
  padding-right: 0;
}

:deep(.dialog-from .el-dialog__header) {
  padding: 11px 17px;
  background-color: #f2f2f2;
  font-size: 18px;
}

.dialog-from :deep(.el-dialog__body) {
  padding-left: 48px;
  padding-right: 48px;
  padding-top: 20px;
}

.body-item {}



.box-title {
  margin-bottom: 10px;
}

.box-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  background-color: #027db4;
  margin-right: 10px;
}



.box-content {
  /* height: 80px; */
}

.row-item {
  height: 80px;
  /* margin-bottom: 20px; */
}

.input-time {
  display: inline-block;
  border-radius: 0;
  margin-top: 0;
  box-shadow: 0 0 0 1px #dcdfe6;
  width: 120px;
  height: 25px;
}

.input-time:hover {
  box-shadow: 0 0 0 1px #c0c4cc;
}

.upload-demo {
  position: relative;
  display: inline-block;
  width: 100%;
}

.upload-demo :deep(.el-upload) {
  width: 100%;
}

.input-upload {
  width: 100%;
}

:deep(.dialog-set .el-dialog__body) {
  padding: 0 27px;
}

.body-set-item {
  margin-top: 20px;
  padding: 0 31px;
}

.box-set-color {
  display: inline-block;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #02A7F0;
  margin-right: 10px;
}

.box-content-item {
  padding-left: 20px;
  font-size: 12px;
}

:deep(.set-input .el-input__wrapper) {
  padding: 0;
  border-radius: 0;
}

:deep(.set-input .el-input__wrapper .el-input__inner) {
  text-align: center;
}

.set-select {
  width: 90px;
}

:deep(.set-select .el-select__wrapper) {
  font-size: 12px;
  padding: 0 5px 0 0;
  text-align: center;
  border-radius: 0;
}
</style>
